package org.misalen.web.database.repository.mysql;

import java.util.Date;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.misalen.utils.TextUtil;
import org.misalen.web.database.dao.mysql.impl.BaseMySqlDaoImpl;
import org.misalen.web.database.model.mysql.pro.ProWebReward;
import org.misalen.web.database.util.PaginationFrom;
import org.springframework.stereotype.Repository;

@Repository
public class ProWebRewardRepository extends BaseMySqlDaoImpl<ProWebReward> {

	public void saveList(int[] is, String primaryKey) {
		Date date = new Date();
		for (int i : is) {
			ProWebReward proVideoReward = new ProWebReward();
			proVideoReward.setAddTime(date);
			proVideoReward.setMoney(i);
			proVideoReward.setTimeLimit(TextUtil.booleanToString(false));
			proVideoReward.setWebId(primaryKey);
			save(proVideoReward);
		}
	}

	public long getValidCountByWeb(String webId) {
		return count("select count(*) from ProWebReward where userId IS NULL and webId=?0", new Object[] { webId });
	}

	public ProWebReward getByVideoUser(String userId, String webId) {
		return get("from ProWebReward where userId=?0 and webId=?1", new Object[] { userId, webId });

	}

	public ProWebReward getValidByVideo(String webId) {
		return get("from ProWebReward where userId IS NULL and webId=?0", new Object[] { webId });
	}
	
	public PaginationFrom<ProWebReward> getMyDetailList(String webId,
			PaginationFrom<ProWebReward> pagination) {
		StringBuffer selectBuffer = new StringBuffer();
		selectBuffer.append("SELECT A.*,B.userName ");
		selectBuffer.append(" FROM ProWebReward A left join ProUser B ");
		selectBuffer.append(" ON A.userId=B.primaryKey ");
		selectBuffer.append(" WHERE A.userId IS NOT NULL ");
		selectBuffer.append(" AND A.webId = '" + webId + "' ");
		selectBuffer.append(" ORDER BY A.addTime desc");
		Session session = this.openSession();
		SQLQuery query = session.createSQLQuery(selectBuffer.toString());
		query.setResultTransformer(new AliasToBeanResultTransformer(ProWebReward.class));
		StringBuffer countBuffer = new StringBuffer();
		countBuffer.append("select count(*) from (" + selectBuffer + ") T");
		pagination.setTotal(Long.valueOf(session.createSQLQuery(countBuffer.toString()).uniqueResult().toString()));
		setResultIndex(query, pagination.getPage(), pagination.getRows());
		@SuppressWarnings("unchecked")
		List<ProWebReward> list = query.list();
		pagination.setList(list);
		closeSession(session);
		return pagination;
	}
}